package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

type myHandler struct {
	http.Handler
}

func main() {
	//创建处理管理器
	mux := http.NewServeMux()
	//重新定向处理
	rh := http.RedirectHandler("http://example.org", 307)
	mux.Handle("/foo", rh)
	th := &timeHandler{format: time.RFC1123}
	mux.Handle("/time", th)
	//Fri, 21 Apr 2017 15:51:49 CST
	th1123 := &timeHandler{format: time.RFC1123}
	mux.Handle("/time/rfc1123", th1123)
	//2017-04-21T15:52:15+08:00
	th3339 := &timeHandler{format: time.RFC3339}
	mux.Handle("/time/rfc3339", th3339)
	log.Println("Listening...")
	//自定义服务器配置 添加处理器
	main_server := &http.Server{
		Addr:           ":8080",
		Handler:        mux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	fmt.Println(main_server)
	//执行监听 并处理完关闭
	log.Fatal(main_server.ListenAndServe())
}

/*自定义处理器*/
type timeHandler struct {
	format string
}

func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tm := time.Now().Format(th.format)
	w.Write([]byte("The time is: " + tm))
}
